package org.springframework.prospring.ticket.web;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.WebUtils;
import org.springframework.prospring.ticket.service.*;
import org.springframework.prospring.ticket.domain.location.Region;
import org.springframework.validation.Errors;
import org.springframework.validation.BindException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;

/**
 * Form controller issuing a ReservationRequest on behalf of the user.
 * The user has selected a show, a price band and a date in the previous
 * screen(s) and this form controller will create the reservation
 * request based on this. Together with the amount of seats the user will
 * be selected, this form controller completes the request.<p>
 *
 * Input:
 * <ul>
 *   <li><code>performanceId</code>: the performance identifier</li>
 *   <li><code>priceBandId</code>: the price band identifier</li>
 * </ul>
 * Error conditions:
 * <ul>
 *  <li>When not enough seats are available anymore</li>
 * </ul>
 */
    public class ReserveFieldController extends AbstractReservationFieldRequestController {

    /*
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.formBackingObject");
        }

        return getReservationRequestFromSession(request);
    }

    /**
     * Binds the maximum number of seats the user will be able to select
     * (key = <code>maximumSeats</code>) and hte default selected value
     * (<code>defaultSelected</code>).
     */
    protected Map referenceData(HttpServletRequest request, Object o, Errors errors) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.referenceData");
        }
        ReservationFieldRequest reservationFieldRequest = (ReservationFieldRequest)o;

        //request.getSession().getServletContext()
        //alexis tenes  poner la lista de los deportes en el contexto de la app
        WebUtils.setSessionAttribute(request, "reservationFieldRequest", reservationFieldRequest );

        Map m = new HashMap();
        m.put("regions", reservationFieldRequest.getRegions());

        return m;
    }

    /**
     * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(
     *      javax.servlet.http.HttpServletRequest,
            javax.servlet.http.HttpServletResponse,
            Object,
            org.springframework.validation.BindException)
     */
    protected ModelAndView onSubmit(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        Object o, BindException errors) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.onSubmit");
        }


        // the object is an already filled in reservation reservationFieldRequest
        ReservationFieldRequest reservationFieldRequest = (ReservationFieldRequest)o;


        // if errors occured showing the form view with the error messages.
        if ("sss" == null) {
            return showForm(httpRequest, errors, getFormView());
        }

        // putting the reservation and performance in session, for future reference.
        WebUtils.setSessionAttribute(httpRequest, "reservationFieldRequest", reservationFieldRequest);

        // redirecting the another controller that will show the reservation.
        // this is done to prevent the user from resubmitting the form.
        reservationFieldRequest.setSuccessView(getSuccessView());

        ModelAndView mav = new ModelAndView(new RedirectView(getSuccessView()));
        if (logger.isDebugEnabled()) {
            logger.debug("ModelAndView: "+mav.toString());
        }

        return mav;
    }


    //====================================== Helper Method (some used for testing) ====================================

    /**
     * Creates a new ReservationRequest with the given values. This method can be used
     * in test cases to overriden and by that mock the created reservation request.
     * @param regions The regions that could be selecte to do a field's reservation.
     * @return A new reservation field request.
     */
/*    protected ReservationFieldRequest createReservationFieldRequest(Collection<Region> regions) {
        if (logger.isDebugEnabled()) {
            logger.debug("ReserveFieldController.createReservationFieldRequest");
        }

        ReservationFieldRequest reservationFieldRequest = new ReservationFieldRequest();

        reservationFieldRequest.setSuccessView(getSuccessView());
        reservationFieldRequest.setRegions(regions);

        return reservationFieldRequest;
    }*/

}
